﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using BaseHelper.Base;

namespace BaseHelper.Net
{
    public class AliyunSmsHelper
    {

        private static string endpoint = "dysmsapi.aliyuncs.com";   // 阿里云服务器地址
        private static string accessKeyId = "";      // 密匙ID
        private static string accessKeySecret = ""; // 密匙

        public static string AccessKey
        {
            set { accessKeyId = value; }
        }

        public static string AccessSecret
        {
            set { accessKeySecret = value; }
        }

        public static string SendSms(string mobile,Hashtable ht ,string SignName,string TempID)
        {

            string json = JsonHelper.Encode(ht);

            // UrlEncode的特殊转换
            Func<string, string> specialUrlEncode = (string temp) =>
            {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < temp.Length; i++)
                {
                    string t = temp[i].ToString();
                    string k = System.Web.HttpUtility.UrlEncode(t, Encoding.UTF8);
                    if (t == k)
                    {
                        stringBuilder.Append(t);
                    }
                    else
                    {
                        stringBuilder.Append(k.ToUpper());
                    }
                }

                return stringBuilder.ToString().Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");
            };

            string nowDate = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");//GTM时间
            System.Collections.Generic.Dictionary<string, string> keyValues = new System.Collections.Generic.Dictionary<string, string>();//声明一个字典

            #region 系统参数
            keyValues.Add("SignatureMethod", "HMAC-SHA1");
            keyValues.Add("SignatureNonce", Guid.NewGuid().ToString()); // ==========
            keyValues.Add("AccessKeyId", accessKeyId);
            keyValues.Add("SignatureVersion", "1.0");
            keyValues.Add("Timestamp", nowDate);
            keyValues.Add("Format", "Json");//可换成xml
            #endregion

            #region 业务api参数
            keyValues.Add("Action", "SendSms");
            keyValues.Add("Version", "2017-05-25");
            keyValues.Add("RegionId", "cn-hangzhou");
            keyValues.Add("PhoneNumbers", mobile);
            keyValues.Add("SignName", SignName);
            keyValues.Add("TemplateParam", json);
            keyValues.Add("TemplateCode", TempID);
            keyValues.Add("OutId", "123");
            #endregion

            //去除签名关键字Signature key
            if (keyValues.ContainsKey("Signature"))
            {
                keyValues.Remove("Signature");
            }

            // 参数key排序
            System.Collections.Generic.Dictionary<string, string> ascDic = keyValues.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value.ToString());

            #region 构造待签名的字符串
            StringBuilder builder = new StringBuilder();
            foreach (var item in ascDic)
            {
                if (item.Key == "SignName")
                {
                }
                else
                {
                    builder.Append("&").Append(specialUrlEncode(item.Key)).Append("=").Append(specialUrlEncode(item.Value));
                }
                if (item.Key == "RegionId")
                {
                    builder.Append("&").Append(specialUrlEncode("SignName")).Append("=").Append(specialUrlEncode(keyValues["SignName"]));
                }
            }
            string sorteQueryString = builder.ToString().Substring(1);
            #endregion

            StringBuilder stringToSign = new StringBuilder();
            stringToSign.Append("GET").Append("&");
            stringToSign.Append(specialUrlEncode("/")).Append("&");
            stringToSign.Append(specialUrlEncode(sorteQueryString));

            #region macsha加密
            var hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret + "&"));
            var dataBuffer = Encoding.UTF8.GetBytes(stringToSign.ToString());
            var hashBytes = hmacsha1.ComputeHash(dataBuffer);
            string stringbyte = BitConverter.ToString(hashBytes, 0).Replace("-", string.Empty).ToLower();
            string hexString = stringbyte.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] bytes = new byte[hexString.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
                bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

            string Sign = Convert.ToBase64String(bytes);
            #endregion

            // 签名特殊URL编码
            string signture = specialUrlEncode(Sign);

            // 格式化GET请求的URL
            string url = string.Format("http://{0}/?Signature={1}{2}", endpoint, signture, builder);

            #region 请求发送短信
            string strRet = string.Empty;
            if (url == null || url.Trim().ToString() == "")
            {
                return strRet;
            }
            string targeturl = url.Trim().ToString();
            try
            {
                HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(targeturl);
                hr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
                hr.Method = "GET";
                hr.Timeout = 30 * 60 * 1000;
                WebResponse hs = hr.GetResponse();
                Stream sr = hs.GetResponseStream();
                StreamReader ser = new StreamReader(sr, Encoding.UTF8);

                strRet = ser.ReadToEnd();
            }
            catch (Exception ex)
            {
                strRet = "短信发送失败！" + ex.Message;
            }
            #endregion

            return strRet;
        }
    }
}
